package org.ngmj.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;
import org.ngmj.protocol.MessageCodecSharable;
import org.ngmj.protocol.ProtocolFrameDecoder;
import org.ngmj.server.handler.*;

@Slf4j
public class Server {
    public static void main(String[] args) {
        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();
        MessageCodecSharable CODEC_SHARABLE = new MessageCodecSharable();
        LoggingHandler LOGGING_HANDLER = new LoggingHandler(LogLevel.DEBUG);
        LoginRequestHandler LOGIN_HANDLER = new LoginRequestHandler();
        ChatRequestHandler CHAT_HANDLER = new ChatRequestHandler();
        GroupChatRequestHandler  GROUP_CHAT_HANDLER = new GroupChatRequestHandler();
        GroupCreateRequestHandler  GROUP_CREATE_HANDLER = new GroupCreateRequestHandler();
        GroupMembersRequestHandler GROUP_MEMBERS_HANDLER = new GroupMembersRequestHandler();
        GroupJoinRequestHandler GROUP_JOIN_HANDLER = new GroupJoinRequestHandler();
        GroupQuitRequestHandler GROUP_QUIT_HANDLER = new GroupQuitRequestHandler();
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<NioSocketChannel>() {
                        @Override
                        protected void initChannel(NioSocketChannel channel) {
                            channel.pipeline().addLast(new ProtocolFrameDecoder());
//                            channel.pipeline().addLast(LOGGING_HANDLER);
                            channel.pipeline().addLast(CODEC_SHARABLE);
                            channel.pipeline().addLast(LOGIN_HANDLER);
                            channel.pipeline().addLast(CHAT_HANDLER);
                            channel.pipeline().addLast(GROUP_CHAT_HANDLER);
                            channel.pipeline().addLast(GROUP_CREATE_HANDLER);
                            channel.pipeline().addLast(GROUP_MEMBERS_HANDLER);
                            channel.pipeline().addLast(GROUP_JOIN_HANDLER);
                            channel.pipeline().addLast(GROUP_QUIT_HANDLER);
                        }
                    }).bind(8080).sync().channel().closeFuture().sync();
        } catch (Exception e) {
            log.error("server error", e);
            throw new RuntimeException(e);
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }

    }
}